/**
 * Created by Ession on 2016/12/15.
 */
var company = {
    events:{
        ".settingBtn click":"saveCompanyInfo"
    },
    settings:{
        CompanyInfo:{},
        imgBlock:"<div class='co-imageBlock'><input name='homeImgs' type='file'/><div class='img-mask'><i class='fa fa-trash-o'></i></div></div>",
        imgBlockOn: function (id) {
            var url = interfaceURL.getImageById()+"?id="+id;
            return "<div class='co-imageBlock on' data-id='"+id+"'><img src='"+url+"'></img><input type='file' name='homeImgs'/><div class='img-mask'><i class='fa fa-trash-o'></i></div></div>"
        },
        imgOn: function (id) {
            var url = interfaceURL.getImageById()+"?id="+id;
            return "<img src='"+url+"'></img>"
        }
    },
    init: function () {
        var _this = this;
        document.title = "公司信息 - 信息管理";
        _this.initCompanyInfo(function (data) {
            var temp = Util.template($("#company-template").html(),{data:data});
            $(".commonBody-rightBody").html(temp);
            Util.event.call(_this,_this.events);

            if(!Util.isEmpty(data.homeImgs_Ids)){
                var $images = $(".co-imageBlock");
                $.each(data.homeImgs_Ids, function (i, n) {
                    if($images.eq(i).length != 0){
                        $images.eq(i).append(_this.settings.imgOn(n)).addClass("on").attr("data-id",n);
                    }else{
                        $("#uploadImg").before(_this.settings.imgBlockOn(n))
                    }
                })
            }
            if(!Util.isEmpty(data.logoFileId)){
                $(".showLogo").html(_this.settings.imgOn(data.logoFileId))
            }

            $("#getLogo").click(function () {
                $("#logoFile").trigger("click").off("change").change(function () {
                    //_this.loadFile(this);//TODO
                    _this.showImg($("#logoFile")[0], function (image) {
                        $(".showLogo").html(image);
                    });
                    $(this).addClass("update");
                })
            });
            $("#uploadImg").click(function () {
                var $block = $(".co-imageBlock:not(.on):first");
                if($block.length == 0){
                    $block = $(_this.settings.imgBlock);
                    $(this).before($block);
                }
                $block.find("input").trigger("click").off("change").change(function () {
                    _this.showImg(this, function (image) {
                        $block.append(image).addClass("on")
                    });
                })
            });
            $(".setting-content").delegate(".co-imageBlock i.fa-trash-o","click", function () {
                var img = $(this).parents(".co-imageBlock");
                pop.confirm("是否删除该图片？", function () {
                    Util.ajaxRequest({
                        type: "get",
                        url: interfaceURL.deleteImg(),
                        dataType: "json",
                        data:{
                          id:img.attr("data-id")
                        },
                        success: function (data) {
                            if(data.code==200){
                                img.hide(300, function () {
                                    img.remove();
                                })
                            }
                        }
                    });
                })
            })
        });
    },
    initCompanyInfo: function (fn) {
        var _this = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getCompany(),
            dataType: "json",
            success: function (data) {
                if(data.code==200){
                    _this.settings.CompanyInfo = data.result;
                    $.isFunction(fn)?fn(data.result):"";
                }
            }
        });
    },
    saveCompanyInfo: function () {
        var _this = this;
        var nameZh = $("#COCHName").val();
        var nameEn = $("#COENName").val();
        var principal = $("#principal").val();
        var fax = $("#fax").val();
        var tel = $("#phone").val();
        var logoId = $("#logoFile").attr("data-id");
        $("#myCompanyInfo").ajaxSubmit({
            type: 'post',
            url: interfaceURL.saveCompany(),
            data:{
                nameZh:nameZh,
                nameEn:nameEn,
                principal:principal,
                fax:fax,
                tel:tel,
                id:_this.settings.CompanyInfo.id,
                homeimgId:"",
                logoId:Util.isEmpty(logoId)?"":logoId
            },
            success: function(data){
                if(data.code == 200){
                    pop.mAlert("修改成功")
                }else{
                    pop.alert("保存失败");
                }
            }
        })
    },
    showImg: function (input,fn) {
        var inputFile = input;
        var reader = new FileReader();
        reader.readAsDataURL(inputFile.files[0]);
        reader.onload = function (e) {
            var base64 = this.result.split(",")[1];
            var image = "<img src='"+this.result+"'></img>";
            $.isFunction(fn)?fn(image,this.result,base64):"";
        };
    },
    loadFile: function (input) {

        var fso = new ActiveXObject("Scripting.FileSystemObject");
        console.log(fso);
        //var f1 = fso.GetFile("c:\\myjstest.txt");

        if (false) {//window.FileReader
            var file = input.files[0];
            var filename = file.name.split(".")[0];
            var reader = new FileReader();
            reader.onloadend = function() {
                console.log(this)
                console.log(this.result.split("\r\n").slice(0,10).join(" "));
                //alert(this.result);
            };
            reader.onloadstart = function (a,b) {

            };
            reader.onabort = function () {
                console.log("终止啦,是的");
                console.log(this)
            };
            //reader.readAsArrayBuffer(file);//,"GBK"
            reader.readAsDataURL(file);
            setTimeout(function () {
                reader.abort();
            },1000)
        }
    },
    CSVToArray: function (strData, strDelimiter ) {
        strDelimiter = (strDelimiter || ",");
        var objPattern = new RegExp(( "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + "([^\"\\" + strDelimiter + "\\r\\n]*))" ), "gi");
        var arrData = [[]];
        var arrMatches = null;
        while (arrMatches = objPattern.exec( strData )){
            var strMatchedDelimiter = arrMatches[ 1 ];
            if (strMatchedDelimiter.length &&(strMatchedDelimiter != strDelimiter)){
                arrData.push( [] );
            }
            if (arrMatches[ 2 ]){
                var strMatchedValue = arrMatches[ 2 ].replace(new RegExp("\"\"", "g" ), "\"");
            } else {
                var strMatchedValue = arrMatches[ 3 ];
            }
            arrData[ arrData.length - 1 ].push( strMatchedValue );
        }
        return( arrData );
    },
    a: function () {

    }
};
